/* Get catalog list asynchronously */
var catalogList_init = function () {
	var $catalog = $('#catalog').siblings('.menu'),
		$defult_text = $('.default.text');

	$.myAjax(
		_CTX_PATH_ + '/note/catalogs/list',
		'',
		function (data) {
			if (data.result == true) {
				$catalog.empty().append(data.catalogList);
				$defult_text.text('请选择分类...');
			} else {
				$defult_text.text('您还没有分类！');
			}
			/*Show dropdown list*/
			$('.ui.dropdown').dropdown();
		}, 'get'
	);
}

/* Submit note function */ 
var submit_note = function () {
	var catalog = $.trim($('#catalog').val()),
		content = $.trim($('#content').val()),
		tags 	= $.trim($('#tags').val()),
		$note 	= $('#note');

	// Change form on loading state
	$note.addClass('loading');

	$.myAjax(
		_CTX_PATH_ + '/note/add',
		{
			catalogId : catalog,
			content : content,
			tags 	: tags
		}, function (data) {
			$note.removeClass('loading');
			if (data.result == true) {
				$('#menu').sidebar('hide');
				alert('添加笔记成功!')
			} else {
				$note.form('add errors', data.error).addClass('error');
			}
		}
	);
}

var sidebar_init = function () {
	var $menu = $('#menu');
	
	$menu.sidebar({onShow : catalogList_init})
		.sidebar('attach events', '.launch.button, .launch.item');
	
	$('#note').form({
		content : {
			identifier : 'content',
			rules : [
				{
					type : 'empty',
					prompt : '笔记内容不能为空，请填写内容'
				},
				{
					type : 'maxLength[600]',
					prompt : '笔记内容长度不能超过600'
				}
			]
		},
		catalog : {
			identifier : 'catalog',
			rules : [
				{
					type : 'empty',
					prompt : '请选择笔记分类'
				},
				{
					type : 'isNumeric',
					prompt : '笔记分类不合法'
				}
			]
		}
	}, {
		onSuccess : submit_note
	});
}

/*Attach ready event*/
$(document).ready(sidebar_init);
